var ss_temp = ""; // test
/////////////////////////ViewModel
var ss_viewModel_min = kendo.observable({
    calDays: function(e) {
        return SmartStream.calDays(e);           
    },
    getTitleId: function(e) {
        return "ss_min_btn_title_" + e.NotificationId;
    },
    getTopicImgId: function(e) {
        return "ss_min_btn_left_img" + e.NotificationId;
    },
    onTitleClick: function(e) {
        if(e.data.IsdetailPageLink==true)
            wp_iframe_win.openIframWindow(e.data.EntityLinkUrl,e.data.NotificationTitle);
        else
            SmartStream.showDetailWindow(e.data);
    },
    getEntityImageUrl: function(e) {
        //if(e.AdditionalData!=""){
            
        if(e.IsdetailPageLink==true)
            return e.EntityImageUrl.trim();
        else
            return "imgs/icons/main_documents_g_20_20.png";
    },
    onToNameClick: function(e) {
        if(e.data.NotificationType == "U")
            homepageProfileWin.user_info_win_create(e.data.ToId);
        else 
            Workport.utils.alertMsg("", "Community profile page - Coming soon!", function(_data){});
    },
    ss_topic_min_ds:new kendo.data.DataSource({
        transport:{
            read:function(operation){
                operation.success(SmartStream.getMinData());
                //SmartStream.loading(false);

            }
        }
    })
});



var ss_viewModel_max = kendo.observable({
    //ID
    getTitleId: function(e) {
        return "ss_max_btn_title_" + e.NotificationId;
    },
    getTopicImgId: function(e) {
        return "ss_max_btn_left_img" + e.NotificationId;
    },
    getTextId: function(e) {
        return "ss_max_btn_text_" + e.NotificationId;
    },
    getLikeId: function(e) {
        return "ss_max_btn_like_" + e.NotificationId;
    },
    getLiekCountId: function(e) {
        return "ss_max_btn_like_count_" + e.NotificationId;
    },
    getBookmarkId: function(e) {
        return "ss_max_btn_bookmark_" + e.NotificationId;
    },
    getCommentId: function(e) {
        return "ss_max_btn_comment_" + e.NotificationId;
    },
    getSubscribeId: function(e) {
        return "ss_max_btn_subscribe_" + e.NotificationId;
    },
    getShareId: function(e) {
        return "ss_max_btn_share_" + e.NotificationId ;
    },
    getDeleteId: function(e) {
        return "ss_max_btn_delete_" + e.NotificationId;
    },
    getInputId: function(e) {
        return "ss_max_btn_input_" + e.NotificationId;
    },
    getReplyId: function(e) {
        return "ss_max_btn_reply_" + e.NotificationId;
    },
    getSelectFileFieldId: function(e) {
        return "ss_topic_select_file_" + e.NotificationId;
    },
    getSelectFileId: function(e) {
        return "ss_topic_select_file_field_" + e.NotificationId;
    },
    getSelectFileNameId: function(e) {
        return "ss_topic_select_file_name_" + e.NotificationId;
    },
    getSelectFileTableId: function(e) {
        return "ss_topic_select_file_table_" + e.NotificationId;
    },

    getSelectIconExpandId: function(e) {
        return "ss_topic_bottom_icon_expand_" + e.NotificationId;
    },
    getSelectFileAttachId: function(e) {
        return "ss_topic_select_file_btn_attach_" + e.NotificationId;
    },
    getOtherCommentId: function(e) {
        return "ss_max_btn_other_comment_" + e.NotificationId;
    },
    getCommentLikeCountId: function(e) {
        return "ss_max_btn_comment_like_count_" + this.get('currentData').NotificationId + "_" + e.CommentId;
    },
    getCommentLikeId: function(e) {
        return "ss_max_btn_comment_like_" + this.get('currentData').NotificationId + "_" + e.CommentId;
    },
    getCommentDivId: function(e) {
        return "ss_max_div_comment_" + e.NotificationId;
    },
    calDays: function(e) {
        return SmartStream.calDays(e);
    },
    calCommentDays: function(e) {
        return SmartStream.calDays(e);
    },
    getTags: function(e) {
        return SmartStream.getTags(e);
    },
    hasAttachment: function(e) {
        //return true;//for test
        // if(e.AdditionalData){
        //     return true;
        // }
        if(e.Attachments==null&&e.Images==null)
            return false;
        if(e.Attachments!=null&&e.Attachments.length!=0){
            return true;
        }
        return (e.Images!=null&&e.Images.length!=0);
    },
    hasComment: function(e) {
        return (ss_parseIntNaN(e.CommentCount)>0);
    },
    hasLike : function(e) {
        return (ss_parseIntNaN(e.LikesCount)>0);
    },
    hasOtherComment:false,
    showInput: true,
    showInputArea:false,
    textAreaValue:"",
    currentData:[],
    getMailhref: function(e) {
        return "mailto:?subject="+e.NotificationTitle+"&body="+e.NotificationText+"%0d%0aYou can access the post directly from here";
    },
    isHasHandClass: function(e) {
        if(e.LikesCount>0)
            return "ss_topic_hand";
        else
            return "";
    },
    isBookMarkedClass: function(e) {
        if(e.IsBookMarked)
            return "ss_topic_hand main_smartstream_ab_8_8";
        else
            return "ss_topic_hand main_smartstream_aa_8_8";
    },
    isSubscribedClass: function(e) {
        if (e.IsSubscribed)
            return "ss_topic_hand main_calendar_t_8_8";//"main_smartstream_o_8_8";
        else
            return "ss_topic_hand main_calendar_u_8_8";//"main_smartstream_n_8_8";
    },
    isLikedTitle: function(e) {
        if(e.IsLiked||e.Liked)
            return "You have Liked this";
        else
            return "Like this";
    },
    isLikedClass: function(e) {
        if(e.IsLiked||e.Liked)
            return "main_smartstream_t_8_8";//wp_mt_4
        else
            return "main_smartstream_w_8_8";
    },
    isCommentLikedClass: function(e) {
        if(e.IsLiked||e.Liked)
            return "main_smartstream_t_8_8";//wp_mt_4
        else
            return "main_smartstream_w_8_8";
    },
    isCommentedClass: function(e) {
        if(e.isCommented)
            return "main_smartstream_u_8_8";
        else
            return "main_smartstream_v_8_8";
    },
    getSubscribeTitle: function(e) {
        if (e.IsSubscribed)
            return "Stop Mail Alerts";
        else
            return "Receive Mail Alerts";
    },
    genAttachment: function(e) {
        // sslog(e);
        var count_td = 0;
        var new_tr = false;
        var html = '';
        //sslog(e.AdditionalData);
        // if(e.AdditionalData!=null&&e.AdditionalData!="")
        // {
        //     html = e.AdditionalData;
        //     return html;
        // }
        // Attachment
        if(e.Attachments!=null){

            for(var j=0;j<e.Attachments.length;j++){
                if (count_td % 4 == 0) {
                    html += '<tr class="wp_h_30">'
                }
                count_td ++;
                var row_fileExt ;
                if(e.Attachments[j].Type)
                    row_fileExt = e.Attachments[j].Type;
                else
                    row_fileExt = "doc";//default

                //= ;//e.Attachments[j].RefURL.replace(/^.*[\\\.]/, '');
                var row_fileName = e.Attachments[j].Name;
                //".pdf, .doc, .docx, .ppt, .pptx, .xls, .xlsx, .txt, .zip"
                html += '<td class="left wp_w_20">';
                if(row_fileExt=="docx"||row_fileExt=="doc"){
                    html += '<a class="ss_topic_hand" target="_blank" onclick="FileViewer.load(\''+e.Attachments[j].RefURL+'\',\''+row_fileName+'\',\''+row_fileExt+'\')"><i class="main_documents_e_20_20"></i></a>';
                } else if(row_fileExt=="tif"||row_fileExt=="tiff"){
					html += '<a class="ss_topic_hand" target="_blank" onclick="FileViewer.load(\''+e.Attachments[j].RefURL+'\',\''+row_fileName+'\',\''+row_fileExt+'\')"><i class="main_documents_t_20_20"></i></a>';
				} else if (row_fileExt=="xlsx"||row_fileExt=="xls") {
                    html += '<a class="ss_topic_hand" target="_blank" onclick="FileViewer.load(\''+e.Attachments[j].RefURL+'\',\''+row_fileName+'\',\''+row_fileExt+'\')"><i class="main_documents_o_20_20"></i></a>';
                } else if(row_fileExt=="pdf"){
                    html += '<a class="ss_topic_hand" target="_blank" onclick="FileViewer.load(\''+e.Attachments[j].RefURL+'\',\''+row_fileName+'\',\''+row_fileExt+'\')"><i class="main_documents_f_20_20"></i></a>';
                }else if(row_fileExt=="ppt"||row_fileExt=="pptx"){
                    html += '<a class="ss_topic_hand" target="_blank" onclick="FileViewer.load(\''+e.Attachments[j].RefURL+'\',\''+row_fileName+'\',\''+row_fileExt+'\')"><i class="main_big_k_20_20"></i></a>';
                }else if(row_fileExt=="txt"){
                    html += '<a class="ss_topic_hand" target="_blank" onclick="FileViewer.load(\''+e.Attachments[j].RefURL+'\',\''+row_fileName+'\',\''+row_fileExt+'\')"><i class="main_big_n_20_20"></i></a>';
                }else if(row_fileExt=="zip"){
                    html += '<a class="ss_topic_hand" target="_blank" onclick="FileViewer.load(\''+e.Attachments[j].RefURL+'\',\''+row_fileName+'\',\''+row_fileExt+'\')"><i class="main_big_m_20_20"></i></a>';
                }else {
                    html += '<a class="ss_topic_hand" target="_blank" onclick="FileViewer.load(\''+e.Attachments[j].RefURL+'\',\''+row_fileName+'\',\''+row_fileExt+'\')"><i class="main_documents_e_20_20"></i></a>';
                }

                html += '</td><td class="left wp_w_140 ss_lh_25" >';

                html += '<p title="'+row_fileName+'" class="wp_fz_11 wp_ml_5 wp_w_130 wp_mt_ne2 text-overflow">'+'<a target="_blank" class="ss_a ss_topic_hand" onclick="FileViewer.load(\''+e.Attachments[j].RefURL+'\',\''+row_fileName+'\',\''+row_fileExt+'\')" title="'+row_fileName+'">'+row_fileName+'</a></p>';
                html += '</td>';
                if (count_td % 4 == 0) {
                    html += '</tr>';
                }
            }
        }
        // Images
        if(e.Images!=null){

            for(var k=0;k<e.Images.length;k++){
                if (count_td % 4 == 0) {
                    html += '<tr class="wp_h_30">'
                }
                count_td ++;

                //var row_fileExt = e.Image[k].replace(/^.*[\\\.]/, '');
                //var row_fileName = e.Image[k].replace(/^.*[\\\/]/, '');
                var imageSrc = e.Images[k].RefURL.replace(/\*.*/,"");
                var row_fileExt = imageSrc.replace(/^.*[\\\.]/, '');
                var row_fileName = e.Images[k].Name;//imageSrc.replace(/^.*[\\\/]/, '');
                var imageThumb= e.Images[k].RefURL.replace(/^.*[\*]/,"");

                html += '<td class="left wp_w_20">';
                if(row_fileExt=="jpg"||row_fileExt=="jpeg"||"row_fileExt==bmp"||row_fileExt=="png"){
                    // html += '<a href='+e.Image[k]+'><img class="wp_w_20 wp_h_20 wp_mt_1" src="'  + e.Image[k] + '" onerror="onDefaultThumbnailWanted(this, \'i\')"/></a>';
                    html += '<a class="ss_topic_hand" target="_blank" onclick="FileViewer.load(\''+imageSrc+'\',\''+row_fileName+'\',\''+row_fileExt+'\')"><img class="wp_w_20 wp_h_20 wp_mt_1" onerror="onDefaultThumbnailWanted(this, \'i\')"'+ "src='"+imageThumb+"'/></a>";
                }
                html += '</td><td class="left wp_w_140 ss_lh_25" >';
                html += '<p title="'+row_fileName+'" class="wp_fz_11 wp_ml_5 wp_w_130 wp_mt_ne3 text-overflow"><a class="ss_a ss_topic_hand" title="'+row_fileName+'" target="_blank" onclick="FileViewer.load(\''+imageSrc+'\',\''+row_fileName+'\',\''+row_fileExt+'\')">'+row_fileName+'</a></p>';
                html += '</td>';

                if (count_td % 4 == 0) {
                    html += '</tr>';
                }

            }
        }

        if (count_td % 4 != 0) {
            html += '</tr>';
        }

        return html;
    },
    commentVisible: false,
    parseIntNaN: function(val) {
        return ss_parseIntNaN(val);
    },
    recentLikedUsers:function(){
        var result ="";
        var likes = this.get("ss_topic_max_likedusers_ds.data()");
        if(likes.length == 0)
            return result;
        var show_num = 3;
        var total = likes[0].LikedUsersDetails.length;
        var _span_s = '<span class="wp_dynimac_text ss_topic_detail_blue_text ss_topic_hand" ';
        var _span_e = '</span>';

        if(total <=0||likes[0].LikedUsersDetails==null){
            return result;
        }
        for (var i = 0; i < total; i++) {
            var _span = _span_s +' onclick="homepageProfileWin.user_info_win_create(\''+likes[i].LikedUsersDetails[i].UserID+'\')" >'+likes[i].LikedUsersDetails[i].UserName + _span_e;
            result = result + _span;
            if(i == (show_num-1)){
                if(total!=show_num)
                    result = result + ' and ' + _span_s +' onclick="alert(\'To be continue\')" >' + (total-show_num) + _span_e +' Other';
                break;
            }
            if(i+1 < total)
                result = result + ' , ';
        }
        return result;
    },
    getEntityImageUrl: function(e) {
        if(e.AdditionalData!=""){
            return e.EntityImageUrl.trim();
        }
        else
            return "imgs/icons/main_documents_g_20_20.png";
    },
    onTitleClick: function(e) {// title click event

        if(e.data.IsdetailPageLink&&e.data.AdditionalData!=""){
            wp_iframe_win.openIframWindow(e.data.EntityLinkUrl,e.data.NotificationTitle);
        }else
            SmartStream.showDetailWindow(e.data);
    },
    onTextClick: function(e) { // text click event
        if(e.data.IsdetailPageLink&&e.data.AdditionalData!=""){
            wp_iframe_win.openIframWindow(e.data.EntityLinkUrl,e.data.NotificationTitle);
        }else
            SmartStream.showDetailWindow(e.data);
    },
    onToNameClick: function(e) {
        if(e.data.NotificationType == "U")
            homepageProfileWin.user_info_win_create(e.data.ToId);
        else
            Workport.utils.alertMsg("", "Community profile page - Coming soon!", function(_data){});
    },
    onFromNameClick: function(e) {
        homepageProfileWin.user_info_win_create(e.data.FromId);
    },
    onDeleteClick: function(e) { // delete click event
        //lin Delete: target ID is notification's TOID
        SmartStream.ss_topic_delete(e.data.NotificationId,e.data.NotificationType,e.data.ToId);
    },
    onCommentClick: function(e) { // comment click event


        sslog("onCommentClick");
        SmartStream.showDetailWindow(e.data);
        return ;
        this.set('currentData',e.data);
        var ds = this.get('ss_topic_max_ds');
        var edata = e.data;
        var index = ds.indexOf(edata);

        if(ds.data()[index].get("commentVisible")==true){
            // hide
            ssshowInput(ds.data()[index],true);
            ds.data()[index].set("commentVisible",false);
            return ;
        }
        // close all
        for (var i = 0; i < ds.data().length; i++) {
            if(i == index)
                ds.data()[i].set("commentVisible",true);
            else
                ds.data()[i].set("commentVisible",false);
        }
        var NotificationId = edata.NotificationId;
        SmartStream.ssClearAttchmentView(NotificationId);

        $("#ss_topic_select_file_field_"+NotificationId).kendoUpload({
            localization: {
                select: "Browse"
            },
            select: function(e) {
                //var shareWinFileAppointType = ".pdf.doc.docx.ppt.pptx.xls.xlsx.txt.zip.jpg.jpeg.png.gif.bmp.tiff";
                sslog(e.files[0]);
                var fileType;
                var alertMsg;
                $('#ss_topic_select_file_name_'+NotificationId).val('');
                $('#ss_topic_select_file_btn_attach_'+NotificationId).addClass("k-state-disabled");

                var shareWinFileAppointType = SmartStream.getShareWinFileAppointType();
                shareWinFileAppointType.indexOf("jpg") > -1 ? fileType = 0 : fileType = 1;
                fileType == 0 ? alertMsg = "The image must be of type bmp, gif, jpeg, png, tiff" : alertMsg = "The file must be of type doc, docx, pdf, ppt, pptx, txt, xls, xlsx, zip";
                var specialChar = ["#", "%", "&", "*", ":", "<", ">", "?", "/", "{", "|", "}"]
                for (var i = 0; i < specialChar.length; i++) {
                    sslog(e.files[0].name);
                    if (e.files[0].name.indexOf(specialChar[i]) > -1) {

                        Workport.utils.alertMsg("", 'The attachment name cannot contain any of the following special characters: \"\\ ~# % & * :” < > ? / { | }\" . Please rename and try again.', function(_data){});
                        e.preventDefault();
                        return;
                    }
                }

                //Check the file type
                if (shareWinFileAppointType.indexOf(e.files[0].extension.toLowerCase().substring(1)) < 0) {
                    Workport.utils.alertMsg("", alertMsg + shareWinFileAppointType, function(_data){});
                    e.preventDefault();
                    return;
                }


                // Check file size < 50MB
                if (e.files[0].size > (50 * 1024 * 1024)) {
                    fileType == 0 ? Workport.utils.alertMsg("", "The size of the image must be within <50 MB>.", function(_data){}) : Workport.utils.alertMsg("", "The size of the attachment must be within <50 MB> .", function(_data){});
                    e.preventDefault();
                    return;
                }
                // Check file count < 5
                var fileCount = 0;
                var shareWinSelectedFileName = SmartStream.getSelectedFileName();



                for (var i = 0; i < shareWinSelectedFileName.length; i++) {
                    if (fileType == 0 && shareWinSelectedFileName[i].type.match(/image.*/)) {
                        fileCount = fileCount + 1;
                    } else if (fileType == 1 && !shareWinSelectedFileName[i].type.match(/image.*/)) {
                        fileCount = fileCount + 1;
                    }
                    // Check same file name

                    if (e.files[0].name== shareWinSelectedFileName[i].name) {
                        Workport.utils.alertMsg("", "A attachment with the same name already exists. Please rename the attachment and try again.", function(_data){});
                        e.preventDefault();
                        return;
                    }
                }
                if (fileCount >= 5) {
                    $('#ss_topic_select_file_name_'+NotificationId).find('span.k-filename[title="' + e.files[0].name + '"]').parent().remove();
                    fileType == 0 ? Workport.utils.alertMsg("", "You can only select five Image files!", function(_data){}) : Workport.utils.alertMsg("", "You can only select five documents!", function(_data){});
                    e.preventDefault();
                    return;
                }
                // $("#ss_topic_select_file ul li:last").hide();
                $('#ss_topic_select_file_name_'+NotificationId).val(e.files[0].name);


                if ($("#ss_topic_select_file_"+NotificationId+" ul li:last").is(':hidden')) {
                    $("#ss_topic_select_file_field_"+NotificationId).closest('td').find('ul').remove();
                }
                /*if ($("#ss_topic_select_file_"+index+" ul li:last").is(':hidden')) {
                    $("#ss_topic_select_file_"+index+" ul li:last").remove();
                }*/

                $('#ss_topic_select_file_btn_attach_'+NotificationId).removeClass("k-state-disabled");
            },
            remove: function(e) {
                var ss_SelectedFileName = SmartStream.getSelectedFileName();
                var ss_SelectedFileContents = SmartStream.getSelectedFileContents();

                for (var i = 0; i < ss_SelectedFileName.length; i++ ) {
                    if (ss_SelectedFileName[i].name == e.files[0].name) {
                        ss_SelectedFileName.splice(i, 1);
                        ss_SelectedFileContents.splice(i, 1);
                    }
                }
                //button enabled

                 if ($("#ss_topic_select_file_field_"+NotificationId).parent().hasClass("k-upload-button-disable")) {
                    $('.k-upload-sync').find('input:file:last').prop('disabled', false);
                    $(".k-upload-button>input").css("cursor","pointer");
                    $("#ss_topic_select_file_field_"+NotificationId).parent().removeClass("k-upload-button-disable");
                }

                if (ss_SelectedFileName.length == 0) {

                        $("#ss_topic_select_file_"+NotificationId+" ul").css("display", 'none');
                        //$("#ss_topic_detail_comment table").addClass("k-widget");
                }
            }
        });
        $('#ss_topic_select_file_name_'+NotificationId).val("");
        $('.k-upload-files').hide();
        $('.k-files').hide();
        SmartStream.ssmaxCommentRead(e.data,true,function(respCode){
            if(respCode=="WP1001"){
                ds.data()[index].set("hasOtherComment",true);
            }else
                ds.data()[index].set("hasOtherComment",false);
        });

    },
    onAttachmentPicClick: function (e) {
        var NotificationId =e.data.NotificationId;
        var ds = this.get('ss_topic_max_ds');
        var index = ds.indexOf(e.data);
        if ($($(e.currentTarget).closest("div").find("i")[0]).hasClass("header_win_e_10_10")) {
            return;
        } else {
            SmartStream.setShareWinFileAppointType("jpg, jpeg, png, gif, bmp, tiff");
            $($(e.currentTarget).closest("div").find("i")[0]).toggleClass("main_calendar_k_10_10 header_win_e_10_10");
            $(e.currentTarget).toggleClass("ss_share_win_detail_arrow ss_topic_detail_hand");

            if ($($(e.currentTarget).closest("div").find("i")[1]).hasClass("header_win_f_10_10")) {
                $($(e.currentTarget).closest("div").find("i")[1]).toggleClass("main_calendar_m_8_10 header_win_f_10_10");
                $($(e.currentTarget).closest("div").find("a")[1]).toggleClass("ss_share_win_detail_arrow ss_topic_detail_hand");
            }
        }

        if ($('#ss_topic_select_file_table_'+NotificationId).is(':hidden')) {
            $("#ss_topic_select_file_table_"+NotificationId).show();
            $("#ss_topic_select_file_name_"+NotificationId).show();
        }
    },
    onAttachmentFileClick: function (e) {
        var ds = this.get('ss_topic_max_ds');
        var index = ds.indexOf(e.data);
        if ($($(e.currentTarget).closest("div").find("i")[1]).hasClass("header_win_f_10_10")) {
            return;
        } else {
            SmartStream.setShareWinFileAppointType("pdf, doc, docx, ppt, pptx, xls, xlsx, txt, zip");

            $($(e.currentTarget).closest("div").find("i")[1]).toggleClass("main_calendar_m_8_10 header_win_f_10_10");
            $(e.currentTarget).toggleClass("ss_share_win_detail_arrow ss_topic_detail_hand");


            if ($($(e.currentTarget).closest("div").find("i")[0]).hasClass("header_win_e_10_10")) {
                $($(e.currentTarget).closest("div").find("i")[0]).toggleClass("main_calendar_k_10_10 header_win_e_10_10");
                $($(e.currentTarget).closest("div").find("a")[0]).toggleClass("ss_share_win_detail_arrow ss_topic_detail_hand");
            }
        }
        var NotificationId = e.data.NotificationId;
        if ($('#ss_topic_select_file_table_'+NotificationId).is(':hidden')) {
            $("#ss_topic_select_file_table_"+NotificationId).show();
            $("#ss_topic_select_file_name_"+NotificationId).show();
        }
    },
    onAttachClick: function (e) {
	
        var ds = this.get('ss_topic_max_ds');
        var index = ds.indexOf(e.data);

        var NotificationId = e.data.NotificationId;
        if ($("#ss_topic_select_file_name_"+NotificationId).val() == "") {
            return;
        }

        $('.k-upload-files').show();
        $("#ss_topic_select_file_name_"+NotificationId).val("");

        var shareWinFileSize = SmartStream.getSelectedFileName().length;//$("#ss_topic_select_file_table_"+NotificationId+" ul li").size() - 1;
        var shareWinMaxAttechmentCount = 9; ////Can choose the number of attachments, Starting from 0
        // button disabled, Can't choose the file
        if (shareWinFileSize == shareWinMaxAttechmentCount) {
            // $(".k-upload-sync").addClass("k-state-doors");
            $('.k-upload-sync').find('input:file:last').prop('disabled', true);
            $(".k-upload-button>input").css("cursor","default");
            $("#ss_topic_select_file_field_"+NotificationId).parent().addClass("k-upload-button-disable");
        }
        //ss_temp = $("#ss_topic_select_file_"+NotificationId+" ul li:last");
        $("#ss_topic_select_file_table_"+NotificationId+" ul li:last").show();

        //get attachment base64 encode
        var shareWinFileReader = new FileReader();
        shareWinFileReader.onload = function(e) {

            // var img = e.target.result;
                // $("#homepage_user_select_img_win_body img").attr("src", img);
            SmartStream.getSelectedFileContents().push(e.target.result.replace(/^.*?,/,''));
        }

        var shareWinSelectedAttechment = $("#ss_topic_select_file_table_"+NotificationId).find('.k-file:last').data().fileNames[0].rawFile;
        shareWinFileReader.readAsDataURL(shareWinSelectedAttechment);
        var selectedFileName = SmartStream.getSelectedFileName().push(shareWinSelectedAttechment);
        $('#ss_topic_select_file_btn_attach_'+NotificationId).addClass("k-state-disabled");
		
    },
    onSubscribeClick: function (e) {
        sslog("onSubscribeClick");
        var p = this;
        var edata = e.data;
        var ds = this.get('ss_topic_max_ds');
        var index = ds.indexOf(edata);
        if(index<0)
        {
            sslog("onSubscribeClick->e:"+e);
            return ;
        }

        SmartStream.subscribeTopic(edata, function () {
            edata.IsSubscribed = !edata.IsSubscribed;
            SmartStream.getMaxData()[index].IsSubscribed = edata.IsSubscribed ;
            ds.data()[index].set("IsSubscribed",edata.IsSubscribed);
            ds.data()[index].set("isSubscribedClass",p.isSubscribedClass(edata));
            ds.data()[index].set("getSubscribeTitle",p.getSubscribeTitle(edata));
        });
    },
    onBookMarkClick: function(e) { // bookmark click event
        sslog("onBookMarkClick");
        var p = this;
        var edata = e.data;
        /*
        if(edata.IsBookMarked)
        {
            sslog(">bookmarked return");
            return ;
        }
        */
        var ds = this.get('ss_topic_max_ds');
        var index = ds.indexOf(edata);
        if(index<0)
        {
            sslog("onBookMarkClick->e:"+e);
            return ;
        }

        SmartStream.bookmarkTopic(edata,function(){
            // change value
            edata.IsBookMarked = !edata.IsBookMarked;
            SmartStream.getMaxData()[index].IsBookMarked = edata.IsBookMarked;
            ds.data()[index].set("IsBookMarked",edata.IsBookMarked);
            // change icon
            ds.data()[index].set("isBookMarkedClass",p.isBookMarkedClass(edata));
        });

    },
    onLikeClick: function(e) {// like click event
        sslog("onLikeClick");
        var p = this;
        var edata = e.data;
        if(edata.IsLiked)
        {
            sslog(">liked return;");
            return;
        }
        var ds = this.get('ss_topic_max_ds');
        var index = ds.indexOf(edata);
        if(index<0)
        {
            sslog("onLikeClick->e:"+e);
            return ;
        }
        SmartStream.likeTopic(edata,"","",function(){
            edata.IsLiked = !edata.IsLiked;

            SmartStream.getMaxData()[index].IsLiked = edata.IsLiked;
            SmartStream.getMaxData()[index].LikesCount = ss_parseIntNaN(edata.LikesCount)+1;

            ds.data()[index].set("LikesCount",ss_parseIntNaN(edata.LikesCount)+1);
            //edata.LikesCount = ss_parseIntNaN(edata.LikesCount)+1;
            ds.data()[index].set("isLikedClass",p.isLikedClass(edata));
            ds.data()[index].set("isLikedTitle",p.isLikedTitle(edata));
            ds.data()[index].set("isHasHandClass",p.isHasHandClass(edata));
            ds.data()[index].set("hasLike",true);


            if(ds.data()[index].get("commentVisible")==true){
                SmartStream.ssmaxCommentRead(edata,true,function(respCode){
                    if(respCode=="WP1001"){
                        ds.data()[index].set("hasOtherComment",true);

                    }else {
                        ds.data()[index].set("hasOtherComment",false);
                    }
                });
            }
        });
    },
    onInputClick: function(e) {
        sslog("onInputClick");
        var edata = e.data;
        var ds = this.get('ss_topic_max_ds');
        var index = ds.indexOf(edata);

        /*
        var tooltipId = $("#ss_max_btn_input_"+edata.NotificationId);
        if(tooltipId.data("kendoTooltip")){
            tooltipId.data("kendoTooltip").destroy();
        }*/
        if(index<0)
        {
            sslog("onInputClick->e:"+e);
            return ;
        }
        if(ds.data()[index].get("showInput")==undefined || ds.data()[index].get("showInput") == true)
        {
            ssshowInput(ds.data()[index],false);
            $(e.target).parent().find("iframe").attr("id","ss_topic_comment_iframe_"+edata.NotificationId);
            $(e.target).closest('table').find('textarea').data("kendoEditor").value('');
            $(e.target).closest('table').find('textarea').data("kendoEditor").focus();
        }

    },
    onReplyClick: function(e) {
        sslog("onReplyClick");
        var edata = e.data;
        var ds = this.get('ss_topic_max_ds');
        var index = ds.indexOf(edata);
        if(index<0)
        {
            sslog("onReplyClick->e:"+e);
            return ;
        }
        var tooltipId ;
        //if($(e.target).closest('table').find('textarea').attr('style')=="display: none;")
        if(ds.data()[index].get("showInput")==undefined || ds.data()[index].get("showInput") == true)
        {
            //vi
            tooltipId = $("#ss_max_btn_input_"+edata.NotificationId);
        }else {
            tooltipId = $(e.target).closest('table').find(".k-editable-area");
        }

        var comment = $(e.target).closest('table').find('textarea').data('kendoEditor').value();
        /*
        if(tooltipId.data("kendoTooltip")){
            tooltipId.data("kendoTooltip").destroy();
        }
        */
        var commentRep = comment.replace(new RegExp("&nbsp;","gm"),"").trim();
        //if(comment==""||commentRep==""||commentRep=="<br />"){
        if(Workport.utils.getRealLength(comment)==0){
            tooltipId.kendoTooltip({
                content: 'Please input the comment text.' ,
                position: "right",
                autoHide: true,
                //autoHide: false,
                //showOn: "click",
                hide: function() {
                    tooltipId.data('kendoTooltip').destroy();
                }
            });
            tooltipId.data('kendoTooltip').show();
            return ;
        }

        if(Workport.utils.getRealLength(comment)>20000){
            tooltipId.kendoTooltip({
                content: 'The length of comment must be less than 20000.' ,
                position: "right",
                autoHide: true,
                hide: function() {
                    tooltipId.data('kendoTooltip').destroy();
                }
            });
            tooltipId.data('kendoTooltip').show();
            return ;
        }
        if(tooltipId.data('kendoTooltip'))
            tooltipId.data('kendoTooltip').destroy();

        /////////////////////////////////attachment begin

        var shareWinApiName = 'Stream/UpdateGeneric';
        var attachContents = new Array(), imageContents = new Array();
        var fileContent, fileSuffix;
        var types = ['jpeg','jpg','gif','bmp', 'png','tiff','tif','pdf','docx','doc','pptx','ppt','xlsx','xls','txt','zip'];
        var hasAttachment = false;
        var ss_SelectedFileName = SmartStream.getSelectedFileName();
        var ss_SelectedFileContents = SmartStream.getSelectedFileContents();
        for (var i = 0; i < ss_SelectedFileName.length; i++) {
            fileContent = new Object();

            fileContent.AttachmentName = ss_SelectedFileName[i].name.substr(0, ss_SelectedFileName[i].name.lastIndexOf("."));
            fileContent.Attachmentbytes = ss_SelectedFileContents[i];

            fileSuffix = ss_SelectedFileName[i].name;
            fileSuffix = fileSuffix.substr(fileSuffix.lastIndexOf(".") + 1);
            $.inArray(fileSuffix, types) > -1 ? fileContent.AttachmentType = fileSuffix : null;
            ss_SelectedFileName[i].type.match(/image.*/) ? imageContents.push(fileContent) : attachContents.push(fileContent);
        };

        comment = comment.replace(new RegExp("&nbsp;","g")," ");

        if(imageContents.length>0||attachContents.length>0)
        {
            var targetId ;
            if(isUserType(edata.NotificationType))
                targetId = edata.FromId;
            else
                targetId = edata.CommunityId;
            /*
            var data ={
            id: e.NotificationId,
            type: e.NotificationType,
            text:comment,
            targetId: e.ToId
            };
            */
            var data = {
                //comment
                "id":edata.NotificationId,//Notification id for which the comments belongs/  parent notification ID
                "type": edata.NotificationType,//U for User to user | C for Community post
                "text4Comment": comment,
                "targetId4Comment": edata.ToId,//edata.ToId,//user id or Community id
                //update
                "text4Update":edata.NotificationText,
                "targetId4Update":targetId,
                "status": "", //leave it empty
                "subEntity": "Update",//edata.Subentity,//Take sub entity type from the parent notification. Subentity for notification/update is: 12
                //"NotificationText": edata.NotificationText,// leave it empty
                "title": "",// leave it empty
                "tags": "",// leave it empty
                "additionalData":"",// leave it empty
                "entityId": "1",//edata.EntityId,//Take it from the parent notification. Entity Id of the Notification (1-Update)
                "url": '',// leave it empty
                "broadcast": "",// leave it empty
                "attachments": attachContents,
                "images": imageContents
            };
            SmartStream.loading(true);
            Workport.StreamAPI.addCommentWithAttach(function(_c,responseData){
                SmartStream.loading(false);
                if(_c[0]==null||responseData[0]==null){
                    Workport.utils.alertMsg("", "network error", function(_data){});
                    return ;
                }
                if(_c[0].ResponseCode !="WP1008"){
                    Workport.utils.alertMsg("", _c[0].ResponseMessage, function(_data){});
                    return ;
                }
                if (responseData[0].ResponseCode!="WP1008") {
                    Workport.utils.alertMsg("", responseData[0].ResponseMessage, function(_data){});
                    return ;
                }
                $(e.target).closest('table').find('textarea').data('kendoEditor').value("");
                ds.data()[index].set("CommentCount",ss_parseIntNaN(edata.CommentCount)+1);
                SmartStream.getMaxData()[index].CommentCount = ss_parseIntNaN(edata.CommentCount)+1;
                ds.data()[index].set("hasOtherComment",true);
                ds.data()[index].set("hasOtherComment",true);
                SmartStream.ssClearAttchmentView(index);
                SmartStream.refreshListView(true,true);//no cache
            },data);
        }else {
            SmartStream.commentTopic(edata,comment,function(){
                $(e.target).closest('table').find('textarea').data('kendoEditor').value("");
                ds.data()[index].set("CommentCount",ss_parseIntNaN(edata.CommentCount)+1);
                //edata.CommentCount = ss_parseIntNaN(edata.CommentCount)+1;
                SmartStream.ssmaxCommentRead(edata,true,function(respCode){
                    if(respCode=="WP1001"){
                        $(e.target).closest('table').find('textarea').data('kendoEditor').value("");
                        ds.data()[index].set("hasOtherComment",true);
                    }else
                        ds.data()[index].set("hasOtherComment",false);
                });
            });
        }

        /////////////////////////////////attachment end
        /*
        Workport.Communication.put(shareWinApiName, function(responseStatus, responseData){
            if (responseData) {
                if ($.inArray(responseData.ResponseCode, shareWinResponseSuccessCode) == -1) {
                    Workport.utils.alertMsg("", responseData.ResponseMessage, function(_data){});
                } else {
                    SmartStream.ssClearAttchmentView(index);
                    refreshListView(true);
                }
            }
        }, shareWinData);


        SmartStream.commentTopic(edata,comment,function(){
            $(e.target).closest('table').find('textarea').data('kendoEditor').value("");
            ds.data()[index].set("CommentCount",ss_parseIntNaN(edata.CommentCount)+1);
            edata.CommentCount = ss_parseIntNaN(edata.CommentCount)+1;
            SmartStream.ssmaxCommentRead(edata,true,function(respCode){
                if(respCode=="WP1001"){
                    ds.data()[index].set("hasOtherComment",true);
                }else
                    ds.data()[index].set("hasOtherComment",false);
            });
        });
        */

        // Workport.StreamAPI.addCommentWithAttach(handler,request

    },
    onLikeCountClick: function(e) {
        sslog("onLikeCountClick");
        if(e.data.LikesCount>0)
            SmartStream.ss_showLikedUserListDialog(e.data.NotificationId);


    },
    onCommentLikeCountClick: function(e) {
        sslog("onCommentLikeCountClick");
        if(e.data.LikesCount>0)
            SmartStream.ss_showLikedUserListDialog(e.data.CommentId);
    },
    onCommentLikeClick: function(e) {
        var p = this;
        var cdata = this.get('currentData');
        var edata = e.data;
        if(edata.Liked)
        {
            sslog(">liked return;");
            return;
        }
        var ds = this.get('ss_topic_max_comments_ds');
        var index = ds.indexOf(edata);
        if(index<0)
        {
            sslog("onCommentLikeClick->e:"+e);
            return ;
        }
        if(ss_isUndefined(edata.CommentId))
        {
            sslog("onCommentLikeClick->CommentId");
            return ;
        }
        SmartStream.likeTopic(cdata,edata.CommentId,edata.CommunityId,function(){
            edata.Liked = !edata.Liked;
            ds.data()[index].set("LikesCount",ss_parseIntNaN(edata.LikesCount)+1);
            //edata.LikesCount = ss_parseIntNaN(edata.LikesCount)+1;
            ds.data()[index].set("isHasHandClass",p.isHasHandClass(edata));
            ds.data()[index].set("isCommentLikedClass",p.isLikedClass(edata));
            ds.data()[index].set("isLikedTitle",p.isLikedTitle(edata));


        });
    },
    onCekOtherCommentClick: function(e) {
        sslog("onCekOtherCommentClick");
        var edata = e.data;
        var ds = this.get('ss_topic_max_ds');
        var index = ds.indexOf(edata);
        if(index<0)
        {
            sslog("onCekOtherCommentClick->e:"+e);
            return ;
        }

        SmartStream.ssmaxCommentRead(edata,false,function(respCode){
            if(respCode=="WP1001"){
                ds.data()[index].set("hasOtherComment",true);
            }else
                ds.data()[index].set("hasOtherComment",false);
        });
    },
    onTextAreaChange: function(e) {
    },
    ss_topic_max_likedusers_ds: new kendo.data.DataSource({
        transport:{
            read:function(operation){
                operation.success(SmartStream.getMaxLikedUserData());
            }
        }
    }),
    ss_topic_max_comments_ds: new kendo.data.DataSource({
        transport:{
            read:function(operation){
                operation.success(SmartStream.getMaxCommentData());
            }
        }
    }),
    ss_topic_max_ds: new kendo.data.DataSource({
        transport:{
            read:function(operation){

                operation.success(SmartStream.getMaxData());
                //SmartStream.loading(false);
            }
        }
    })
});

//////////////////////////////////////////
var expand_html ;
var expand_parent ;
var SmartStream = (function(){
    //scroll
    var isMoved = false;
    var hideComponent = true;
    var shareWinFileAppointType = "";

    //API parameter
    var ss_topic_offset_min_bottom_val = "";
    var ss_topic_offset_min_top_val = "";
    var ss_topic_latest_min_val = false;
    var ss_topic_offset_max_bottom_val = "";
    var ss_topic_offset_max_top_val = "";
    var ss_topic_latest_max_val = false;
    var ss_topic_ps_val = 10;
    var ss_topic_order_val = false; //20140519 Order value needs to be false for first time.
    var ss_topic_filter = "0";
    var ss_topic_offset_comment_val = "";

    var ss_topic_isFirst = true;
    var ss_topic_load_count = 0;

    //private cache
    var ss_topic_cache_min_val = [];
    var ss_topic_cache_max_val = [];
    var ss_topic_cache_max_comments_val = [];
    var ss_topic_cache_max_likedusers_val = [];

    var ss_SelectedFileName = [];
    var ss_selectedFilePath = [];
    var ss_SelectedFileContents = [];

    var ss_expand_index = 0;

    function ssminRead(isRefresh)
    {
        SmartStream.loading(true);

        $('#ss_topic_began').hide();
        var offset_val ;

        if(isRefresh){
            offset_val = ss_formartDate(ss_topic_offset_min_top_val);
            ss_topic_latest_min_val = ss_topic_offset_min_top_val != [];
        }else {
            offset_val = ss_formartDate(ss_topic_offset_min_bottom_val);
        }
        // offset_val = ss_formartDate(ss_topic_offset_min_bottom_val);
        var _data = {pageSize:ss_topic_ps_val, offset:offset_val, latest:ss_topic_latest_min_val, filter:ss_topic_filter,sync:true };
        Workport.StreamAPI.getBasicStream(function(_d,_code){
            SmartStream.loading(false);
            SmartStream.isFirstLoad();

            if(!_d){
                Workport.utils.alertMsg("", 'network error!', function(_data){});
                return ;
            }
                if(_d.notification==null||_d.notification==""){
                    if(offset_val==""&&!ss_topic_latest_min_val&&ss_topic_filter=="0")
                        $('#ss_topic_began').show();
                        //$("#ss_menubar_share_btn").data('kendoTooltip').show();
                    ss_viewModel_min.ss_topic_min_ds.read();
//                                $("#ss_panel_top_resize").kendoTooltip({
//                                    content: 'Click here to share your first Activity.' ,
//                                    position: "bottom",
//                                    autoHide: false,
//                                    showOn: false
//                });
//                $('#ss_panel_top_resize').bind({
//                    click:function(e){
//                        //HomePage_Scrollable.zoom(0);
//                        return;
//                    }
//                });
//
//                $("#ss_panel_top_resize").data('kendoTooltip').show();
                return;
            }

            ss_topic_offset_min_bottom_val = _d.notification[_d.notification.length - 1].LastModifiedDate;

            ss_topic_latest_min_val = true;
            if(ss_topic_cache_min_val.length ==0)
                ss_topic_cache_min_val = _d.notification;
            else
            {
                for (var j = 0; j < _d.notification.length; j++) {
                    for (var k = 0; k < ss_topic_cache_min_val.length; k++) {
                        if(_d.notification[j].NotificationId == ss_topic_cache_min_val[k].NotificationId){
                            ss_topic_cache_min_val.splice(k,1);// delete it
                        }
                    }
                }
                //insert
                for (var i = 0; i < _d.notification.length; i++) {
                    isRefresh?ss_topic_cache_min_val.splice(i,0,_d.notification[i]):ss_topic_cache_min_val.push(_d.notification[i]);
                    //ss_topic_cache_min_val.push(_d.notification[i]);
                }
            }
            ss_topic_offset_min_top_val = ss_topic_cache_min_val[0].LastModifiedDate;

            ss_viewModel_min.ss_topic_min_ds.read();

        },_data);


        //$("#ss_menubar_share_btn").addClass("ss_topic_hand")
    }

    function ssmaxRead(isRefresh)
    {
        SmartStream.loading(true);

        $('#ss_topic_began').hide();
        ss_topic_cache_max_likedusers_val = [];
        ss_topic_cache_max_comments_val = [];

        var ds = ss_viewModel_max.get('ss_topic_max_ds');
        /*
        ss_temp = ds;
        var ncid = -1;

        for (var i = 0; i < ds.data().length; i++) {
            if(ds.data()[i].get("commentVisible")){
                // ss_expand_ncid = ds.data()[i].get("NotificationId");
                ncid =ds.data()[i].get("NotificationId");
                expand_html = $("#ss_max_div_comment_"+ncid).clone();
                ss_temp = expand_html;
                expand_parent = $("#ss_max_div_comment_"+ncid);//.parent();
            }
        };
        */

        var offset_val ;
        if(isRefresh){
            offset_val = ss_formartDate(ss_topic_offset_max_top_val);
            ss_topic_latest_max_val = ss_topic_offset_max_top_val != [];
        }else {
            offset_val = ss_formartDate(ss_topic_offset_max_bottom_val);
        }

        // offset_val = ss_formartDate(ss_topic_offset_max_bottom_val);

        var order_val = '0*'+ss_topic_order_val;
        var _data = {pageSize: ss_topic_ps_val, offset: offset_val, latest: ss_topic_latest_max_val, filter: ss_topic_filter, order: order_val,sync:true };



        Workport.StreamAPI.getDefaultStream(function(_d,_code){
            SmartStream.loading(false);
            if(!_d){
                Workport.utils.alertMsg("", 'network error!', function(_data){});
                return ;
            }
            if(_d.notification==null||_d.notification==""){
                ss_viewModel_max.ss_topic_max_likedusers_ds.read();
                ss_viewModel_max.ss_topic_max_comments_ds.read();
                ss_viewModel_max.ss_topic_max_ds.read();
                return;
            }
            ss_topic_offset_max_bottom_val = _d.notification[_d.notification.length - 1].LastModifiedDate;

            ss_topic_latest_max_val = true;
            if(ss_topic_cache_max_val.length == 0)
                ss_topic_cache_max_val = _d.notification;
            else
            {

                for (var j = 0; j < _d.notification.length; j++) {
                    for (var k = 0; k < ss_topic_cache_max_val.length; k++) {
                        if(_d.notification[j].NotificationId == ss_topic_cache_max_val[k].NotificationId){
                            ss_topic_cache_max_val.splice(k,1);// delete it

                        }
                    }
                }

                //insert
                for (var i = 0; i < _d.notification.length; i++) {
                    isRefresh?ss_topic_cache_max_val.splice(i,0,_d.notification[i]):ss_topic_cache_max_val.push(_d.notification[i]);
                    //ss_topic_cache_max_val.push(_d.notification[i]);
                }
            }
            ss_topic_offset_max_top_val = ss_topic_cache_max_val[0].LastModifiedDate;

            ss_viewModel_max.ss_topic_max_likedusers_ds.read();
            ss_viewModel_max.ss_topic_max_comments_ds.read();
            ss_viewModel_max.ss_topic_max_ds.read();
            /*
            if(ncid!=-1){
                for (var k = 0; k < ss_topic_cache_max_val.length; k++) {
                    if(ncid == ss_topic_cache_max_val[k].NotificationId){
                        ss_viewModel_max.get('ss_topic_max_ds').data()[k].set("commentVisible",true);
                        //ss_viewModel_max.get('ss_topic_max_ds').data()[k].set("onInputClick",ss_topic_cache_max_val[k]);
                        $("#ss_max_div_comment_"+ncid+" div").remove();

                        expand_html.appendTo($("#ss_max_div_comment_"+ncid));
                    }
                };
            }
            */

        },_data);
    }

    function ssmaxCommentRead(edata,isRefresh,callback) {
        SmartStream.loading(true);

        if (isRefresh) {
            ss_topic_cache_max_likedusers_val = [];
            ss_topic_cache_max_comments_val = [];
            ss_topic_offset_comment_val = "";
        }

        //Stream/{NCid}/Like?ps={ page size}&pn={ page number}
        var _data = {
            id:edata.NotificationId,
            //like
            pageSize4Like:"10",
            PageNumber:"0",
            //comment
            targetId:edata.ToId,
            pageSize4Comment:100,
            offset:ss_topic_offset_comment_val,
            type:edata.NotificationType
        };
        Workport.StreamAPI.getCommentAndLike(function(a,b){
            SmartStream.loading(false);
            if(b[1] == "success"){
                ss_topic_cache_max_likedusers_val = b[0];
            } else {
                Workport.utils.alertMsg("", "Stream//like err", function(_data){});
                return ;
            }
            if(a[1] == "success"){
                if(a[0].ResponseCode=="WP1008"||a[0].ResponseCode=="WP1005"||a[0].ResponseCode=="WP1001")
                {
                    if(a[0].comments.length > 0)
                        ss_topic_offset_comment_val = a[0].comments[a[0].comments.length - 1].LastModifiedDate;
                    if(ss_topic_cache_max_comments_val.length == 0)
                    {
                        ss_topic_cache_max_comments_val = a[0].comments;
                    }else
                    {
                        for (var i = 0; i < a[0].comments.length; i++) {
                            ss_topic_cache_max_comments_val.push(a[0].comments[i]);
                        }
                    }
                    if(callback)
                        callback(a[0].ResponseCode);
                }
            } else {
                Workport.utils.alertMsg("", "Stream/Comment err", function(_data){});
                return ;
            }

            ss_viewModel_max.ss_topic_max_likedusers_ds.read();
            ss_viewModel_max.ss_topic_max_comments_ds.read();

        },_data);
        /*
        urls.push({url:Workport.utils.obj2url('Stream/'+edata.NotificationId+'/Like',likeData),method:'get'});
        urls.push({url:Workport.utils.obj2url('Stream/'+edata.NotificationId+'/Comment',{ tid: edata.ToId, ps: 100, offset:ss_topic_offset_comment_val,ntype:edata.NotificationType}),method:'get'});

        Workport.Communication.batch(urls,function(a,b){
            if(a[1] == "success"){
                ss_topic_cache_max_likedusers_val = a[0];
            } else {
                Workport.utils.alertMsg("", "Stream//like err", function(_data){});
                return ;
            }
            if(b[1] == "success"){
                if(b[0].ResponseCode=="WP1008"||b[0].ResponseCode=="WP1005"||b[0].ResponseCode=="WP1001")
                {
                    if(b[0].comments.length > 0)
                        ss_topic_offset_comment_val = b[0].comments[b[0].comments.length - 1].LastModifiedDate;
                    if(ss_topic_cache_max_comments_val.length == 0)
                    {
                        ss_topic_cache_max_comments_val = b[0].comments;
                    }else
                    {
                        for (var i = 0; i < b[0].comments.length; i++) {
                            ss_topic_cache_max_comments_val.push(b[0].comments[i]);
                        }
                    }
                    if(callback)
                        callback(b[0].ResponseCode);
                }
            } else {
                Workport.utils.alertMsg("", "Stream//Comment err", function(_data){});
                return ;
            }


            ss_viewModel_max.ss_topic_max_likedusers_ds.read();
            ss_viewModel_max.ss_topic_max_comments_ds.read();

        });*/
    }

    function _showDetailWindow(data){
        // var createdDate = new Date(data.CreatedDate).format("M/d/yyyy h:m:s TT");
        var createdDate = data.CreatedDate;
        //sslog('detail_win:'+data.NotificationId+','+data.NotificationType+','+data.ToId+','+createdDate);
        show_ss_topic_detail_win(data.NotificationId,data.NotificationType,data.ToId,createdDate,data.NotificationText);
    }



    function ssClearAttchmentView(index)
    {
        /*
            $("#share_body_content_to_input").val("");
            $("#share_body_content_subject_input").val("");
            $("#share_body_content_tags_input").val("");
            $("#share_start_date_input").val("");
            $("#share_start_time_input").val("");
            $("#share_end_date_input").val("");
            $("#share_end_time_input").val("");
            $("#share_body_content_location_input").val("");

            $("#share_quick_kendo_editor").data("kendoEditor").value("");
            $("#share_event_kendo_editor").data("kendoEditor").value("");
        */

            var shareWinDelFileSize =$("#ss_topic_select_file_table_"+index+" ul li").size();
            while (shareWinDelFileSize > 0) {
                shareWinDelFileSize--;
                $("#ss_topic_select_file_+"+index+" ul li:eq(" + shareWinDelFileSize + ")").remove();
            }


            $('#ss_topic_select_file_name_'+index).hide();
            $('#ss_topic_select_file_table_'+index).hide();

            if ($($("#ss_topic_bottom_icon_expand_"+index).find("i")[0]).hasClass("header_win_e_10_10")) {
                $($("#ss_topic_bottom_icon_expand_"+index).find("i")[0]).toggleClass("main_calendar_k_10_10 header_win_e_10_10");
                $($("#ss_topic_bottom_icon_expand_"+index).find("a")[0]).toggleClass("ss_share_win_detail_arrow ss_topic_detail_hand");
            }

            if ($($("#ss_topic_bottom_icon_expand_"+index).find("i")[1]).hasClass("header_win_f_10_10")) {
                $($("#ss_topic_bottom_icon_expand_"+index).find("i")[1]).toggleClass("main_calendar_m_8_10 header_win_f_10_10");
                $($("#ss_topic_bottom_icon_expand_"+index).find("a")[1]).toggleClass("ss_share_win_detail_arrow ss_topic_detail_hand");
            }

            if ($(".k-upload-sync").hasClass("k-state-doors")) {
                $(".k-upload-sync").removeClass("k-state-doors");
                $('.k-upload-sync').find('input:file:last').prop('disabled', false);
                $(".k-upload-button>input").css("cursor","pointer");
                $("#ss_topic_select_file_btn_attach_"+index).removeClass("k-state-disabled");
            }

            ss_SelectedFileName = [];
            ss_SelectedFileContents = [];

            shareWinSelectedUserid = ''
            $('#ss_topic_select_file_btn_attach_'+index).addClass("k-state-disabled");
    }



    function _bindMinTopicViewModel(viewid,tmpl){
        $("#ss_view").attr("data-template",tmpl);
        $("#ss_view").attr("data-bind","source: ss_topic_min_ds");

        ss_topic_offset_min_bottom_val = "";
        ss_topic_latest_min_val = false;
        ss_topic_offset_max_bottom_val = "";
        ss_topic_latest_max_val = false;
        ss_topic_cache_min_val = [];
        ss_topic_cache_max_val = [];


        kendo.bind($(viewid), ss_viewModel_min);
        ssminRead();
    }

    //bind topic
    function _bindMaxTopicViewModel(viewid,tmpl){
        $(viewid).attr("data-template",tmpl);
        $(viewid).attr("data-bind","source: ss_topic_max_ds");
        ss_viewModel_user_list_win = kendo.observable({ss_topic_detail_like_user_list:[],onLikeUserClick:function(e){homepageProfileWin.user_info_win_create(e.data.UserID);}});
        kendo.bind($("#ss_topic_user_list_div"), ss_viewModel_user_list_win);

        ssmaxRead();

        kendo.bind($(viewid), ss_viewModel_max);

    }

    function likeTopic(e,coid,cobyid,callback) {
        if(ss_isUndefined(e.NotificationId)||ss_isUndefined(e.ToId)||ss_isUndefined(e.FromId)||ss_isUndefined(e.NotificationType))
        {
            sslog("SmartStream.bookmarkTopic->"+ss_isUndefined(e.NotificationId)+","+ss_isUndefined(e.ToId)+","+ss_isUndefined(e.FromId)+","+ss_isUndefined(e.NotificationType));
            return ;
        }
        /*
        var data ={
            TargetId: e.ToId,
            NotificationId: e.NotificationId,
            NotificationFromID: e.FromId,
            CommentId: coid,
            CommentedByID: cobyid,
            NotificationType: e.NotificationType
        };
        Workport.Communication.post('Stream/Like',
            function(s,_d){
                if(_d.ResponseCode=="WP1008")
                    callback();
                else
                    Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
            },
            data);
        */
        var data ={
            targetId: e.ToId,
            id: e.NotificationId,
            fromId: e.FromId,
            commentId: coid,
            commentedBy: cobyid,
            type: e.NotificationType
        };
        SmartStream.loading(true);
        Workport.StreamAPI.postLike(function(_d,_c){
            SmartStream.loading(false);
            if(_d.ResponseCode=="WP1008")
                callback();
            else
                Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
        },data);
    }

    function commentTopic(e,comment,callback) {

        if(ss_isUndefined(e.NotificationId)||ss_isUndefined(e.ToId)||ss_isUndefined(e.NotificationType))
        {
            sslog("SmartStream.commentTopic->"+ss_isUndefined(e.NotificationId)+","+ss_isUndefined(e.ToId)+","+ss_isUndefined(e.NotificationType));
            return ;
        }
        /*
        var _d ={
            NotificationId: e.NotificationId,
            NotificationType: e.NotificationType,
            CommentText:comment,
            ToID: e.ToId
        };

        Workport.Communication.post('Stream/Comment',
            function(s,_d){
                if(_d.ResponseCode=="WP1008")
                    callback();
                else
                    Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
            },
            _d);
        */

        var data ={
            id: e.NotificationId,
            type: e.NotificationType,
            text:comment,
            targetId: e.ToId
        };
        SmartStream.loading(true);
        Workport.StreamAPI.postComment(function(_d,_c){
            SmartStream.loading(false);
            if(_d.ResponseCode=="WP1008")
                callback();
            else
                Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
        },data);
    }

    function subscribeTopic(e, callback) {
        if(ss_isUndefined(e.NotificationId)||ss_isUndefined(e.ToId)||ss_isUndefined(e.NotificationType))
        {
            sslog("SmartStream.subscribeTopic->"+ss_isUndefined(e.NotificationId)+","+ss_isUndefined(e.ToId)+","+ss_isUndefined(e.NotificationType));
            return ;
        }

        var isSub = "0";
        if(e.IsSubscribed)
            isSub = "1";
        /*
        var data ={
            NotificationID: e.NotificationId,
            CommunityId: e.ToId,
            ActionType: isSub
        };

        Workport.Communication.post('Stream/Subscribe',
            function(s,_d){
                if(_d.ResponseCode=="WP1008")
                    callback();
                else
                    Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
            },
            data);

        */

        var data ={
            id: e.NotificationId,
            communityId: e.ToId,
            action: isSub
        };
        
        if(e.NotificationType.toLowerCase()=="u")
        {
            /*
            Workport.StreamAPI.userSubscribe(function(_d,_c){
                SmartStream.loading(false);
                    if(_d.ResponseCode=="WP1008")
                        callback();
                    else
                        Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
            },data);*/
        }else if(e.NotificationType.toLowerCase()=="c"){
            SmartStream.loading(true);
            Workport.StreamAPI.subscribe(function(_d,_c){
                SmartStream.loading(false);
                    if(_d.ResponseCode=="WP1008")
                        callback();
                    else
                        Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
            },data);
        }
        
    }

    function bookmarkTopic(e,callback) {
        if(ss_isUndefined(e.NotificationId)||ss_isUndefined(e.ToId)||ss_isUndefined(e.NotificationType))
        {
            sslog("SmartStream.bookmarkTopic->"+ss_isUndefined(e.NotificationId)+","+ss_isUndefined(e.ToId)+","+ss_isUndefined(e.NotificationType));
            return ;
        }

        var isMark = "0";
        if(e.IsBookMarked)
            isMark = "1";
        /*
        var data ={
              NotificationId: e.NotificationId,
              CommunityId: e.ToId,
              ActionType: isMark,
              NotificationType: e.NotificationType
        };

        Workport.Communication.post('Stream/Bookmark',
            function(s,_d){
                if(_d.ResponseCode=="WP1008")
                    callback();
                else
                    Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
            },
            data);
        */

        var data ={
            id: e.NotificationId,
            communityId: e.ToId,
            action: isMark,
            type: e.NotificationType
        };
        SmartStream.loading(true);
        Workport.StreamAPI.bookmark(function(_d,_c){
            SmartStream.loading(false);
            if(_d.ResponseCode=="WP1008")
                callback();
            else
                Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
        },data);
    }

    function deleteTopic(data){
        /*
        Workport.Communication.put('Stream/Delete',
            function(s,_d){
                if(_d.ResponseCode=="WP1008"){
                    Workport.utils.alertMsg("", "Your update has been deleted sucessfully.", function(_data){});
                    refreshListView(true);
                }
                else
                    Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
            },
            data);
        */
        SmartStream.loading(true);
        Workport.StreamAPI.deleteStream(function(_d,_c){
            SmartStream.loading(false);
            if(!_d){
                Workport.utils.alertMsg("", 'network error!', function(_data){});
                return ;
            }

            if(_d.ResponseCode=="WP1008"){
                Workport.utils.alertMsg("", "Your update has been deleted sucessfully.", function(_data){
                    //SmartStream.refreshListView(true,true);//no cache
                    for (var k = 0; k < ss_topic_cache_max_val.length; k++) {
                        if(data.id == ss_topic_cache_max_val[k].NotificationId){
                            ss_topic_cache_max_val.splice(k,1);// delete it
                            ss_viewModel_max.ss_topic_max_ds.read();
                            return ;
                        }
                    }
                });
            }
            else
                Workport.utils.alertMsg("", _d.ResponseMessage, function(_data){});
        },data);
    }
    function closeIt (data) {
        // body...
    }
    function ss_topic_delete(nid,ntype,targetId){
        if(ss_isUndefined(nid)||ss_isUndefined(ntype)||ss_isUndefined(targetId))
        {
            sslog("ss_topic_delete->nid:"+nid+",ntype:"+ntype+",targetId:"+targetId);
            return ;
        }
        var divId = 'ss_popup_view';
        var w = 528;
        var h =100;
        var title= "Delete";
        var content = 'Deleting the update will also delete all attachments associated with  the update. Are you sure you want to delete the update?';
        var yesText = "Delete";
        var cancelText = "Cancel";

        var _d ={
            id: nid,
            type: ntype,
            targetId:targetId
        };
        //ss_makeConfirmDialog(divId,w,h,title,content,yesText,cancelText,deleteTopic,closeIt,_d);

        Workport.utils.alertMsg(title,content,yesText,function(_data){
            if(_data==true){
                deleteTopic(_d);
            }
            //Workport.utils.alertMsg("", _data, function(_data){});
        });

    }




    //*****************smartstream viewmodel function ******************************


    function _getTags(e)
    {
      if(e.Tags==null)
      {
        return "null";
      }
      var resultTags = "";
      if(e.Tags.length == 1)
        return e.Tags[0];

      $.each(e.Tags, function(index, tag) {
        if(resultTags == "")
              resultTags = tag;
            else
              resultTags = resultTags + ", " + tag;
        });
      return resultTags;
    }

    function ss_genHtmlTag(e) {
      return 'ncid="'+ e.NotificationId + '" ntype="' + e.NotificationType + '" toid="' + e.ToId + '" commid="' + e.CommunityId + '" CreatedDate="' + e.CreatedDate +'"';
    }

    function ss_parseIntNaN(val)
    {
        return (isNaN(val)||val=="")?0:parseInt(val);
    }
    var ss_likedUserList_val ;
    var ss_viewModel_user_list_win;
    function ss_makeLikedUserListDialog(data)
    {

        ss_viewModel_user_list_win.set("ss_topic_detail_like_user_list",data);
        var ss_topic_detail_user_list_win = $('#ss_topic_user_list_window');

        ss_topic_detail_user_list_win.kendoWindow({
            width:384,
            height:40,
            title:"Liked Users",
            visible:false,
            model:true,
            draggable: false,
            resizable: false,
            modal: true,
            actions:["Close"],
            close:function(){
                ss_viewModel_user_list_win.set("ss_topic_detail_like_user_list",[]);
            }
        });
        ss_topic_detail_user_list_win.data("kendoWindow").center();
        ss_topic_detail_user_list_win.data("kendoWindow").open();
        var height=$("#ss_topic_user_list_window_content").height();
        ss_topic_detail_user_list_win.data("kendoWindow").setOptions({height: $("#ss_topic_user_list_window_content").height()+20});
        if(data.length>8){
            $('#ss_topic_user_list_window_content').slimScroll({
                height: height+'px',
                width:'180px',
				disableFadeOut:true
            });
            $('#ss_topic_user_list_window_content').css("margin-top","10px");
        }else if(data.length==1){
            var thisHeight=height+20+"px";
            $('#ss_topic_detail_user_list_window').css("height",thisHeight);
        }

        /*
        var kendoWindow = $("<div id='ss_topic_userlist_window' />").kendoWindow({
            width:192,
            height:40,
            title:"",
            visible:false,

            resizable: false,
            modal: true,
            actions:["Close"],
            close:function(){

            },
            content  : {
                template: $("#ss_topic_user_list_template").html()
            }
            title    : "Record",
            resizable: false,
            modal    : true,
            viewable : false,
            content  : {
                data:data[0],
                dataType: "json",
                template: $("#ss_topic_user_list_template").html()
            }
        }).data("kendoWindow");
        ss_likedUserList_val = data;
        //kendo.bind(kendoWindow.data, data);
        kendoWindow.open().center();
        */
    }

    function ss_showLikedUserListDialog(id)
    {
        /*
        var likeUsersData={ ps: 10, pn: 0};

        Workport.Communication.get( Workport.utils.obj2url("Stream/"+ id +"/Like",likeUsersData),function(status,result){
            if(result){
                if(result.length>0&&result[0].LikedUsersDetails){
                    if(result[0].LikedUsersDetails.length>0){
                        var data=result[0].LikedUsersDetails;
                        ss_makeLikedUserListDialog(data);
                    }

                }else{
                    Workport.utils.alertMsg("", "LikedUsersDetails is null.", function(_data){});
                }

            }else{
                Workport.utils.alertMsg("", "Liked users list response is Null.", function(_data){});
            }
        });
        */
        var likeUsersData={ targetId:id,pageSize: 10, pageNumber: 0};
        SmartStream.loading(true);
        Workport.StreamAPI.getLikeByNotify(function(result,_c){
            SmartStream.loading(false);
            if(result){
                if(result.length>0&&result[0].LikedUsersDetails){
                    if(result[0].LikedUsersDetails.length>0){
                        var data=result[0].LikedUsersDetails;
                        ss_makeLikedUserListDialog(data);
                    }

                }else{
                    Workport.utils.alertMsg("", "LikedUsersDetails is null.", function(_data){});
                }

            }else{
                Workport.utils.alertMsg("", "Liked users list response is Null.", function(_data){});
            }
        },likeUsersData);
    }

    function ss_makeConfirmDialog(sViewId,w,h,title,content,yesText,cancelText,yesCallback,cancelCallback,data)
    {
        var _popup_view_win = $('#'+sViewId);
        _popup_view_win.kendoWindow({
                    width:w,
                    height:h,
                    title:title,
                    visible:false,
                    resizable: false,
                    modal: true,
                    actions:["Close"], //"Minimize",
                    close:function(){
                        cancelCallback(data);
                    }
        });

        var _popup_viewModel = kendo.observable({
            _content:content,
            _yes:yesText,
            _cancel:cancelText,
            onYes:function(){yesCallback(data);_popup_view_win.data("kendoWindow").close();},
            onCancel:function(){_popup_view_win.data("kendoWindow").close();}
        });

        kendo.bind($('#'+sViewId), _popup_viewModel);
        _popup_view_win.data("kendoWindow").center();
        _popup_view_win.data("kendoWindow").open();
    }







    //////////////////////////////////////////////////////////////////////

    return {
        calDays: function(e){return Workport.utils.calDays(e.CreatedDate,e.ServerDate);},
        showDetailWindow: function(data){_showDetailWindow(data);},
        getTags: function(e){return _getTags(e);},
        ss_topic_delete: function(nid,ntype,targetId){
            ss_topic_delete(nid,ntype,targetId);
        },
        ssClearAttchmentView: function(index){
            ssClearAttchmentView(index);
        },
        ssmaxCommentRead: function(edata,isRefresh,callback){
            ssmaxCommentRead(edata,isRefresh,callback);
        },
        subscribeTopic: function(e, callback){
            subscribeTopic(e, callback);
        },
        bookmarkTopic: function(e,callback){
            bookmarkTopic(e,callback);
        },
        likeTopic: function(e,coid,cobyid,callback){
            likeTopic(e,coid,cobyid,callback);
        },
        ss_showLikedUserListDialog: function(id){
            ss_showLikedUserListDialog(id);
        },
        commentTopic: function(e,comment,callback){
            commentTopic(e,comment,callback);
        },

        bindMinTopicViewModel: function(viewid,tmpl){
            ss_topic_cache_min_val = [];
            ss_topic_cache_max_val = [];

            ss_topic_offset_min_bottom_val = "";
            ss_topic_offset_min_top_val = "";
            ss_topic_offset_max_bottom_val = "";
            ss_topic_offset_max_top_val = "";
            _bindMinTopicViewModel(viewid,tmpl);
        },
        bindMaxTopicViewModel: function(viewid,tmpl){
            ss_topic_cache_min_val = [];
            ss_topic_cache_max_val = [];

            ss_topic_offset_min_bottom_val = "";
            ss_topic_offset_min_top_val = "";
            ss_topic_offset_max_bottom_val = "";
            ss_topic_offset_max_top_val = "";
            _bindMaxTopicViewModel(viewid,tmpl);
        },
        getSelectedFileName: function(){
            return ss_SelectedFileName;
        },
        getSelectedFileContents: function(){
            return ss_SelectedFileContents;
        },
        setHideComponent:function(val){
            hideComponent = val;
        },
        getHideComponent:function(){
            return hideComponent;
        },
        setShareWinFileAppointType:function(val){
            shareWinFileAppointType = val;
        },
        getShareWinFileAppointType:function(){
            return shareWinFileAppointType;
        },
        setIsMoved:function(val){
            isMoved = val;
        },
        getIsMoved:function(){
            return isMoved;
        },
        refreshListView: function(isRefresh,isCleanCache)
        {
            var isMin = hideComponent;
            if(isRefresh){
              if(isMin){

                //ss_topic_cache_min_val = [];
                //ss_topic_offset_min_bottom_val = "";
                ss_topic_latest_min_val = false;
              } else {

                //ss_topic_cache_max_val = [];
                //ss_topic_offset_max_bottom_val = "";
                ss_topic_latest_max_val = false;
              }
            }else {
                ss_topic_latest_min_val = false;
                ss_topic_latest_max_val =  false;
            }

            if(isCleanCache){
                ss_topic_cache_min_val = [];
                ss_topic_cache_max_val = [];

                ss_topic_offset_min_bottom_val = "";
                ss_topic_offset_min_top_val = "";
                ss_topic_offset_max_bottom_val = "";
                ss_topic_offset_max_top_val = "";
            }

            if (isMin) {
              ssminRead(isRefresh);
            } else {
              ssmaxRead(isRefresh);
            }

        },
        setOrderParam: function(){

            ss_topic_order_val = !ss_topic_order_val;
        },
        setFilterParam: function(filter){
            ss_topic_filter = filter;
        },
        getMinData: function(){
            return ss_topic_cache_min_val ? ss_topic_cache_min_val : [];
        },
        getMaxData: function(){
            return ss_topic_cache_max_val ? ss_topic_cache_max_val : [];
        },
        setMaxData: function(data){
            ss_topic_cache_max_val = data;
        },
        isFirstLoad: function(){
            if(ss_topic_isFirst)
            {
                ss_topic_isFirst = false;
                sslog('first');
                setAppCount();
                return true;
            }
            sslog('other');
            return false;
        },
        loading: function(visible){
            return ;
            var isMin = hideComponent;
            sslog('===================='+ new Date());

            $('#ss_load_view').css({
                "top":ss_viewport().height/2,
                "left":$('#ss_view').width()/2
            });

            sslog("+++++++++"+visible+"|"+ss_topic_load_count);

            if(visible){
                ss_topic_load_count = ss_topic_load_count + 1 ;
                if(ss_topic_load_count>0)
                    $('#ss_load_view').show();
            }
            else{
                (ss_topic_load_count>0) ? ss_topic_load_count = ss_topic_load_count - 1 : ss_topic_load_count = 0
                if(ss_topic_load_count<1)
                    $('#ss_load_view').hide();
            }
            sslog("+++++++++"+ss_topic_load_count);

        },
        getMaxCommentData: function(){
            return ss_topic_cache_max_comments_val ? ss_topic_cache_max_comments_val : [];
        },
        getMaxLikedUserData: function(){
            return ss_topic_cache_max_likedusers_val ? ss_topic_cache_max_likedusers_val : [];
        },
        updateByData: function(newData){
            if(hideComponent){
                for (var k = 0; k < ss_topic_cache_min_val.length; k++) {
                    if(newData.NotificationId == ss_topic_cache_min_val[k].NotificationId){
                        ss_topic_cache_min_val.splice(k,1,newData);// replace it
                        ss_viewModel_min.ss_topic_min_ds.read();
                        return ;
                    }
                }
            }else {
                for (var k = 0; k < ss_topic_cache_max_val.length; k++) {
                    if(newData.NotificationId == ss_topic_cache_max_val[k].NotificationId){
                        ss_topic_cache_max_val.splice(k,1,newData);// replace it

                        ss_viewModel_max.ss_topic_max_likedusers_ds.read();
                        ss_viewModel_max.ss_topic_max_comments_ds.read();
                        ss_viewModel_max.ss_topic_max_ds.read();
                        return ;
                    }
                }

            }
        }
    };

}());









